<template>
  <div class="exam-marking-container" v-loading="isLoading">
    <el-card shadow="never" v-if="recordData">
      <template #header>
        <div class="card-header">
          <span>批改试卷 - 记录ID: {{ recordId }} (学生ID: {{ recordData.studentId }})</span>
          <el-button style="margin-left: auto;" @click="goBack">返回列表</el-button>
        </div>
      </template>

      <div class="marking-content">
        <!-- 左侧：题目和作答区域 -->
        <div class="questions-area">
          <h3>试题详情与作答</h3>
          <div v-if="autoGradedQuestions && autoGradedQuestions.length > 0">
            <h4>客观题（已自动评分）</h4>
            <div v-for="(q, index) in autoGradedQuestions" :key="q.questionId" class="question-block auto-graded">
              <p><strong>{{ index + 1 }}. [{{ formatQuestionType(q.type) }} - {{ q.maxScore }}分]</strong> {{ q.content }}</p>
              <p>学生答案: <el-tag>{{ q.studentAnswer }}</el-tag></p>
              <p>正确答案: <el-tag type="success">{{ q.correctAnswer.join(', ') }}</el-tag></p>
              <p>得分: <el-tag type="success">{{ q.score }}</el-tag></p>
            </div>
          </div>

          <el-divider v-if="autoGradedQuestions && autoGradedQuestions.length > 0 && pendingQuestions && pendingQuestions.length > 0"></el-divider>

          <div v-if="pendingQuestions && pendingQuestions.length > 0">
            <h4>主观题（待批改）</h4>
            <div v-for="(q, index) in pendingQuestions" :key="q.questionId" class="question-block manual-graded">
              <p><strong>{{ autoGradedQuestions.length + index + 1 }}. [{{ formatQuestionType(q.type) }} - {{ q.maxScore }}分]</strong> {{ q.content || '题目内容缺失' }}</p>
              <p>学生答案:</p>
              <div class="student-answer-box">{{ q.studentAnswer }}</div>
              
              <div class="marking-inputs">
                 <el-form-item :label="`得分 (满分: ${q.maxScore})`" :prop="`manualScores.${q.questionId}.score`">
                    <el-input-number 
                        v-model="manualScores[q.questionId].score" 
                        :min="0" 
                        :max="q.maxScore" 
                        :precision="1" 
                        :step="0.5"
                        controls-position="right"
                        style="width: 150px;"
                        placeholder="输入分数"
                        :disabled="isMarkingCompleted"
                    />
                 </el-form-item>
                 <el-form-item label="评语" :prop="`manualScores.${q.questionId}.comments`">
                     <el-input 
                        v-model="manualScores[q.questionId].comments" 
                        type="textarea" 
                        :rows="2"
                        placeholder="输入题目评语（可选）"
                         :disabled="isMarkingCompleted"
                    />
                 </el-form-item>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧：评分概览和提交区域 -->
        <div class="summary-area">
          <h3>评分概览</h3>
           <el-descriptions :column="1" border direction="vertical">
                <el-descriptions-item label="客观题得分 (自动)">
                    <el-tag type="success" size="large">{{ autoGradedTotal.toFixed(1) }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="主观题得分 (手动)">
                    <el-tag type="warning" size="large">{{ manualGradedTotal.toFixed(1) }} / {{ pendingTotal.toFixed(1) }}</el-tag>
                </el-descriptions-item>
                 <el-descriptions-item label="最终总分">
                    <el-tag type="danger" size="large">{{ finalTotalScore.toFixed(1) }} / {{ maxPossibleScore.toFixed(1) }}</el-tag>
                </el-descriptions-item>
            </el-descriptions>
            
           <el-divider></el-divider>

           <!-- 新增：考生可疑行为统计 -->
           <h3>考生行为监控</h3>
           <div class="suspicious-behavior-section">
             <el-descriptions :column="1" border direction="vertical" v-if="suspiciousData">
               <el-descriptions-item label="可疑等级">
                 <el-tag :type="getSuspicionTagType(suspiciousData.suspicious_level)" size="large" v-if="suspiciousData.suspicious_level > 0">
                   <el-icon><WarningFilled /></el-icon>
                   等级 {{ suspiciousData.suspicious_level }} - {{ getSuspicionText(suspiciousData.suspicious_level) }}
                 </el-tag>
                 <el-tag type="success" size="large" v-else>
                   <el-icon><CircleCheck /></el-icon>
                   无异常行为
                 </el-tag>
               </el-descriptions-item>
               <el-descriptions-item label="快捷键使用">
                 <el-tag :type="suspiciousData.keyboard_shortcut_count > 0 ? 'warning' : 'success'">
                   {{ suspiciousData.keyboard_shortcut_count || 0 }} 次
                 </el-tag>
               </el-descriptions-item>
               <el-descriptions-item label="复制粘贴">
                 <el-tag :type="suspiciousData.copy_paste_count > 0 ? 'danger' : 'success'">
                   {{ suspiciousData.copy_paste_count || 0 }} 次
                 </el-tag>
               </el-descriptions-item>
               <el-descriptions-item label="切屏行为">
                 <el-tag :type="suspiciousData.tab_switch_count > 0 ? 'danger' : 'success'">
                   {{ suspiciousData.tab_switch_count || 0 }} 次
                 </el-tag>
               </el-descriptions-item>
             </el-descriptions>
             <div v-else class="no-suspicious-data">
               <el-tag type="success">
                 <el-icon><CircleCheck /></el-icon>
                 无行为监控数据
               </el-tag>
             </div>
           </div>

           <el-divider></el-divider>

           <h3>整体评语</h3>
           <el-form-item label="总评语">
               <el-input 
                    v-model="overallComments" 
                    type="textarea" 
                    :rows="4"
                    placeholder="输入对该学生本次考试的整体评语（可选）"
                    :disabled="isMarkingCompleted"
                />
           </el-form-item>

           <div class="actions">
                <el-button 
                    type="primary" 
                    @click="submitMarkingHandler" 
                    :loading="isSubmitting"
                    :disabled="isMarkingCompleted || !isAllPendingMarked"
                    style="width: 100%; margin-top: 20px;"
                >
                    {{ isMarkingCompleted ? '批改已完成' : '提交批改结果' }}
                </el-button>
                <p v-if="!isMarkingCompleted && !isAllPendingMarked" class="warning-text">请完成所有主观题的评分</p>
           </div>

        </div>
      </div>

    </el-card>
    <el-empty v-else-if="!isLoading && !recordData" description="无法加载考试记录数据"></el-empty>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { startMarking, submitMarking, getExamRecords } from '@/services/examService';
import { ElMessage, ElCard, ElButton, ElTag, ElInputNumber, ElInput, ElDivider, ElDescriptions, ElDescriptionsItem, ElFormItem, ElEmpty } from 'element-plus';
import { WarningFilled, CircleCheck } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();

const recordId = ref(route.params.recordId);
const recordData = ref(null); // 存储 startMarking 返回的完整记录数据
const isLoading = ref(false);
const isSubmitting = ref(false);

// 分离后的题目列表
const autoGradedQuestions = ref([]);
const pendingQuestions = ref([]);

// 分数概览
const autoGradedTotal = ref(0);
const pendingTotal = ref(0); // 待批改题目的总分值
const maxPossibleScore = ref(0); // 试卷总分

// 存储手动评分结果 { questionId: { score: null, comments: '' } }
const manualScores = reactive({}); 

// 整体评语
const overallComments = ref('');

// 新增：考生可疑行为统计
const suspiciousData = ref(null);

// --- Computed Properties ---

// 计算手动评分部分的总分
const manualGradedTotal = computed(() => {
  return pendingQuestions.value.reduce((sum, q) => {
    const scoreData = manualScores[q.questionId];
    return sum + (scoreData && typeof scoreData.score === 'number' ? scoreData.score : 0);
  }, 0);
});

// 计算最终总分
const finalTotalScore = computed(() => {
  return autoGradedTotal.value + manualGradedTotal.value;
});

// 检查是否所有待批改题目都已评分
const isAllPendingMarked = computed(() => {
    if (!pendingQuestions.value || pendingQuestions.value.length === 0) {
        return true; // 没有需要手动评分的题目
    }
    return pendingQuestions.value.every(q => {
        const scoreData = manualScores[q.questionId];
        return scoreData && typeof scoreData.score === 'number';
    });
});

// 判断批改是否已完成
const isMarkingCompleted = computed(() => {
    return recordData.value?.markingStatus === 'COMPLETED';
});

// --- Methods ---

// 新增：获取可疑行为数据
const loadSuspiciousData = async () => {
  try {
    // 如果批改数据中已包含examId，从考试记录中获取完整信息
    if (recordData.value && recordData.value.examId) {
      const examId = recordData.value.examId;
      const recordsResponse = await getExamRecords(examId);
      
      if (recordsResponse && recordsResponse.success && recordsResponse.data) {
        // 从记录列表中找到当前记录
        const currentRecord = recordsResponse.data.find(record => 
          record.id === parseInt(recordId.value) || record.id === recordId.value
        );
        
        if (currentRecord) {
          console.log('找到完整考试记录:', currentRecord);
          // 设置可疑行为数据
          suspiciousData.value = {
            keyboard_shortcut_count: currentRecord.keyboardShortcutCount || 0,
            copy_paste_count: currentRecord.copyPasteCount || 0,
            tab_switch_count: currentRecord.tabSwitchCount || 0,
            suspicious_level: currentRecord.suspiciousLevel || 0
          };
          return;
        } else {
          console.warn('在考试记录中未找到对应的记录ID:', recordId.value);
        }
      }
    }
    
    // 回退：从startMarking响应中尝试获取
    if (recordData.value) {
      if (recordData.value.keyboardShortcutCount !== undefined || recordData.value.suspiciousLevel !== undefined) {
        // 如果数据直接在recordData中（使用驼峰命名）
        suspiciousData.value = {
          keyboard_shortcut_count: recordData.value.keyboardShortcutCount || 0,
          copy_paste_count: recordData.value.copyPasteCount || 0,
          tab_switch_count: recordData.value.tabSwitchCount || 0,
          suspicious_level: recordData.value.suspiciousLevel || 0
        };
      } else {
        // 设置默认值
        suspiciousData.value = {
          keyboard_shortcut_count: 0,
          copy_paste_count: 0,
          tab_switch_count: 0,
          suspicious_level: 0
        };
      }
    }
  } catch (error) {
    console.error('获取可疑行为数据失败:', error);
    // 设置默认值
    suspiciousData.value = {
      keyboard_shortcut_count: 0,
      copy_paste_count: 0,
      tab_switch_count: 0,
      suspicious_level: 0
    };
  }
};

const loadMarkingData = async () => {
  if (!recordId.value) {
    ElMessage.error('无效的考试记录ID');
    return;
  }
  isLoading.value = true;
  // 清空旧数据，防止残留
  recordData.value = null;
  autoGradedQuestions.value = [];
  pendingQuestions.value = [];
  autoGradedTotal.value = 0;
  pendingTotal.value = 0;
  maxPossibleScore.value = 0;
  Object.keys(manualScores).forEach(key => delete manualScores[key]); // 清空手动评分
  overallComments.value = '';
  suspiciousData.value = null;

  try {
    const response = await startMarking(recordId.value);
    if (response && response.success && response.data) {
      recordData.value = response.data; // 存储完整记录数据
      overallComments.value = recordData.value.markingComments || ''; // 加载已有的总评语

      // 添加调试信息
      console.log('批改数据响应:', response.data);
      console.log('检查可疑行为字段:', {
        keyboardShortcutCount: response.data.keyboardShortcutCount,
        copyPasteCount: response.data.copyPasteCount,
        tabSwitchCount: response.data.tabSwitchCount,
        suspiciousLevel: response.data.suspiciousLevel
      });

      // 尝试获取可疑行为数据
      await loadSuspiciousData();

      // --- 核心修改：直接处理 response.data.questions 和 response.data.answers --- 
      const questions = response.data.questions;
      const answersStr = response.data.answers;
      let studentAnswersMap = {};

      if (!Array.isArray(questions) || questions.length === 0) {
          ElMessage.warning('考试记录中没有题目数据');
          isLoading.value = false;
          return;
      }

      try {
          if (answersStr) {
              studentAnswersMap = JSON.parse(answersStr);
          } else {
               ElMessage.warning('缺少学生答案数据');
          }
      } catch (parseError) {
          console.error("Error parsing student answers:", parseError);
          ElMessage.error('解析学生答案失败');
          // 可以选择继续处理题目，但无学生答案
      }
      
      const newAutoGradedQuestions = [];
      const newPendingQuestions = [];
      let newAutoGradedTotal = 0;
      let newPendingTotal = 0;
      let newMaxPossibleScore = 0;

      questions.forEach(q => {
          const questionId = q.id;
          const type = q.type;
          const content = q.content;
          const maxScore = q.score || 0;
          const correctAnswers = q.answers || []; // 后端题目本身的答案
          const studentAnswer = studentAnswersMap[questionId]; // 学生对这题的答案

          newMaxPossibleScore += maxScore;

          const baseQuestionData = {
              questionId,
              type,
              content,
              maxScore,
              studentAnswer: studentAnswer !== undefined ? String(studentAnswer) : '未作答', // 统一转字符串或标记未作答
              correctAnswer: correctAnswers // 保留原始正确答案
          };

          if (type === 'SINGLE_CHOICE' || type === 'TRUE_FALSE') {
              let score = 0;
              // 注意：学生答案和正确答案都需要规范化比较
              const normalizedStudentAnswer = String(studentAnswer).toUpperCase();
              const normalizedCorrectAnswers = correctAnswers.map(ans => String(ans).toUpperCase());
              
              if (normalizedCorrectAnswers.includes(normalizedStudentAnswer)) {
                   score = maxScore;
              }
              newAutoGradedTotal += score;
              newAutoGradedQuestions.push({
                  ...baseQuestionData,
                  score,
                  autoGraded: true
              });
          } else if (type === 'FILL_BLANK' || type === 'SHORT_ANSWER') {
               newPendingTotal += maxScore;
               // 查找之前是否已保存过分数（例如继续批改）
               // 这个逻辑需要后端在 startMarking 的 scoringDetails 里提供更准确的已评分信息
               // 暂时先按初始状态处理，score 设为 null 待输入
               newPendingQuestions.push({
                   ...baseQuestionData,
                   score: null, // 待批改，初始分数设为null
                   needsManualGrading: true
               });
               manualScores[questionId] = {
                   score: null,
                   comments: '' // 初始评语为空
               };
          } else {
              console.warn(`Unsupported question type for grading: ${type}`);
              // 可以选择加入待批改或忽略
          }
      });
      
      // 更新状态
      autoGradedQuestions.value = newAutoGradedQuestions;
      pendingQuestions.value = newPendingQuestions;
      autoGradedTotal.value = newAutoGradedTotal;
      pendingTotal.value = newPendingTotal;
      maxPossibleScore.value = newMaxPossibleScore;

      // 如果是继续批改，尝试从 recordData 中恢复手动评分
       if (recordData.value.scoringDetails) {
          try {
              const details = JSON.parse(recordData.value.scoringDetails);
              // 仅用于恢复 manualScores，不再依赖它构建列表
              if (details.pendingQuestions && Array.isArray(details.pendingQuestions)) {
                  details.pendingQuestions.forEach(pq => {
                      if (manualScores[pq.questionId] !== undefined && pq.score !== null && pq.score !== undefined) {
                          manualScores[pq.questionId].score = pq.score;
                          manualScores[pq.questionId].comments = pq.comments || '';
                      }
                  });
              }
          } catch (e) { console.error("Error restoring manual scores from details:", e); }
      } 
      // --------------------------------------------------------------------- 

    } else {
      recordData.value = null; // 清空数据
      ElMessage.error(response?.message || '加载批改数据失败');
    }
  } catch (error) {
    console.error("Error starting marking:", error);
    recordData.value = null;
  } finally {
    isLoading.value = false;
  }
};

// 提交批改结果
const submitMarkingHandler = async () => {
    if (!isAllPendingMarked.value) {
        ElMessage.warning('请完成所有主观题的评分后再提交');
        return;
    }

    isSubmitting.value = true;
    try {
        // 准备 questionScores 数组
        const questionScoresPayload = pendingQuestions.value.map(q => ({
            questionId: q.questionId,
            score: manualScores[q.questionId]?.score ?? 0, // 确保提交的是数字
            comments: manualScores[q.questionId]?.comments || ''
        }));

        // 准备提交的数据
        const payload = {
            score: finalTotalScore.value, // 提交计算出的最终总分
            comments: overallComments.value,
            questionScores: questionScoresPayload
        };

        const response = await submitMarking(recordId.value, payload);

        if (response && response.success) {
            ElMessage.success(response.message || '批改提交成功');
            // 批改成功后可以刷新数据或返回列表
            // loadMarkingData(); // 重新加载数据以更新状态
            router.push({ name: 'ExamRecordsList', params: { id: recordData.value?.examId } }); // 返回记录列表
        } else {
            // 错误已在 service 层处理
        }
    } catch (error) {
         console.error("Error submitting marking:", error);
         // service 层已处理错误消息
    } finally {
        isSubmitting.value = false;
    }
};

// 格式化题目类型 (可以考虑提取到 utils)
const formatQuestionType = (type) => {
  const typeMap = {
    SINGLE_CHOICE: '单选题',
    MULTIPLE_CHOICE: '多选题', // 即使移除了，这里保留以防数据显示旧数据
    TRUE_FALSE: '判断题',
    FILL_BLANK: '填空题',
    SHORT_ANSWER: '简答题'
  };
  return typeMap[type] || type;
};

const goBack = () => {
    // 返回到记录列表页，需要知道 examId
    if (recordData.value && recordData.value.examId) {
        router.push({ name: 'ExamRecordsList', params: { id: recordData.value.examId } });
    } else {
        router.back(); // 如果 examId 不可用，尝试返回上一页
    }
};

// 组件挂载时获取数据
onMounted(() => {
  loadMarkingData();
});

// 新增：考生可疑行为统计
const getSuspicionTagType = (level) => {
  const levelMap = {
    1: 'success',
    2: 'info', 
    3: 'warning',
    4: 'danger',
    5: 'danger'
  };
  return levelMap[level] || 'info';
};

const getSuspicionText = (level) => {
  const levelMap = {
    1: '无风险',
    2: '轻微可疑',
    3: '中等可疑', 
    4: '高度可疑',
    5: '极度可疑'
  };
  return levelMap[level] || '未知风险';
};

</script>

<style scoped>
.exam-marking-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.marking-content {
  display: flex;
  gap: 20px;
}
.questions-area {
  flex: 3; /* 占据更多空间 */
  min-width: 0; /* 防止 flex item 内容溢出 */
}
.summary-area {
  flex: 1;
  min-width: 300px; /* 固定右侧宽度 */
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
}
.question-block {
  margin-bottom: 25px;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}
.question-block.auto-graded {
  background-color: #f0f9eb; /* 浅绿色背景表示自动评分 */
}
.question-block.manual-graded {
  background-color: #fdf6ec; /* 浅黄色背景表示手动评分 */
}
.question-block p {
  margin-bottom: 8px;
  line-height: 1.6;
}
.student-answer-box {
    background-color: #fff;
    border: 1px dashed #dcdfe6;
    padding: 10px;
    border-radius: 4px;
    margin-top: 5px;
    margin-bottom: 15px;
    white-space: pre-wrap; /* 保留换行 */
    word-break: break-word;
}
.marking-inputs .el-form-item {
    margin-bottom: 10px;
}
.summary-area h3 {
    margin-top: 0;
    margin-bottom: 15px;
    font-size: 1.1rem;
}
.warning-text {
    color: #e6a23c;
    font-size: 0.85rem;
    margin-top: 5px;
    text-align: center;
}
.suspicious-behavior-section {
  margin-bottom: 20px;
}
.no-suspicious-data {
  text-align: center;
  padding: 10px;
  background-color: #f0f0f0;
  border-radius: 4px;
}
</style> 